package org.problem7.ccc2009p5;

public class BestWifiCalculator
{

    private int[][] cityIntersections;
    private int numberOfEastWestStreets;
    private int numberOfNorthSouthStreets;
    private int maximalBitRate;
    int numberOfCafesWithMaximalBitRate;

    public void setCityDimensions(int numberOfEastWestStreets, int numberOfNorthSouthStreets)
    {
        this.numberOfEastWestStreets = numberOfEastWestStreets;
        this.numberOfNorthSouthStreets = numberOfNorthSouthStreets;
        cityIntersections = new int[numberOfEastWestStreets + 1][numberOfNorthSouthStreets + 1];
    }

    public int optimalBitRate()
    {
        return maximalBitRate;
    }

    public int numberOfIntersectionWithOptimalBitRate()
    {
        return numberOfCafesWithMaximalBitRate;
    }

    public void addCafe(int x, int y, int radius, int bitRate)
    {
        int xLength = Math.min(numberOfEastWestStreets, x + radius);
        int radiusSqd = radius * radius;
        for ( int i = Math.max(x - radius, 1); i <= xLength; i++ )
        {
            int xDiff = x - i;
            int xDiffSqd = xDiff * xDiff;

            //d^2 = x^2 + y^2
            //y = (d^2 - x^2)^.5
            int absY = (int) Math.sqrt(radiusSqd - xDiffSqd);
            int yLength = Math.min(numberOfNorthSouthStreets, y + absY);
            for ( int j = Math.max(y - absY, 1); j <= yLength; j++ )
            {
                cityIntersections[i][j] = cityIntersections[i][j] + bitRate;
                if ( cityIntersections[i][j] > maximalBitRate )
                {
                    maximalBitRate = cityIntersections[i][j];
                    numberOfCafesWithMaximalBitRate = 0;
                }
                if ( cityIntersections[i][j] == maximalBitRate )
                {
                    numberOfCafesWithMaximalBitRate++;
                }
            }
        }
    }

    @Override
    public String toString()
    {
        StringBuilder sb = new StringBuilder();
        for ( int i = 1; i <= numberOfEastWestStreets; i++ )
        {
            for ( int j = 1; j <= numberOfNorthSouthStreets; j++ )
            {
                sb.append("\t").append(cityIntersections[i][j]);
            }
            sb.append("\n");
        }
        return sb.toString();
    }
}
